<?php
// $Id$

/**
 * @file
 */

/**
 * Menu callback; Present an administrative item listing.
 */
function guild_admin_item_page() {
  $edit = $_POST;
  
  // Return a confirmation form if there were items selected for the delete operation.
  if (isset($edit['operation']) && ($edit['operation'] == 'delete') && isset($edit['items']) && $edit['items']) {
    module_load_include('inc', 'guild', 'includes/guild.admin');
    return drupal_get_form('guild_operation_multiple_delete_confirm');
  }
  
  return drupal_get_form('guild_item_overview');
}

/**
 * Form builder; Item editing page.
 *
 * @param $form_state
 * @param string $op
 *   The editing operation, either 'add' or 'edit'.
 * @param array $item
 *   (optional) If supplied by the menu loader, contains an array with item
 *   values.
 */
function guild_item_edit($form_state, $op, $item = NULL) {
  if (empty($item) || $op == 'add') {
    $item = array(
      'event_template_id' => NULL,
      'name' => '',
      'description' => '',
      'module' => 'guild',
      'type' => 'item',
      'link' => ''
    );
  }
  else {
    drupal_set_title(t('Item: @name', array('@name' => $item['name'])));
  }
  
  $form['item_op'] = array('#type' => 'value', '#value' => $op);
  $form['event_template_id'] = array('#type' => 'value', '#value' => $item['event_template_id']);
  $form['module'] = array('#type' => 'value', '#value' => $item['module']);
  $form['type'] = array('#type' => 'value', '#value' => $item['type']);
  
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Item name'),
    '#default_value' => $item['name'],
    '#maxlength' => 64,
    '#required' => TRUE
  );
  
  $form['link'] = array(
    '#type' => 'textfield',
    '#title' => t('Item link'),
    '#description' => t('This URL must be fully qualified, such as http://example.com.'),
    '#default_value' => $item['link'],
    '#maxlength' => 255
  );
  
  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $item['description'],
    '#rows' => 2
  );
  
  // @todo Determine how to implement item purchases. This particular method
  //   only works if the point system's expense method is fixed.
  
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $op == 'edit' ? t('Update') : t('Create')
  );
  
  return $form;
}

/**
 * Validate an edited item form.
 */
function guild_item_edit_validate($form, &$form_state) {
  $item = $form_state['values'];
  
  if ($item['url']) {
    if (!valid_url($item['url'], TRUE)) {
      form_set_error('url', t('The item URL you have specified is invalid.'));
    }
  }
  
  //if ($item['item_op'] == 'add') {
  //  if (empty($item['event_value'])) {
  //    $item['event_value'] = '0.000';
  //  }
  //  else if (!is_numeric($item['event_value'])) {
  //    form_set_error('event_value', t('The event value must be a number.'));
  //  }
  //  else if (round(abs($item['event_value']), 3) >= 10000) {
  //    form_set_error('event_value', t('The event value must be a number between -9999.999 and 9999.999.'));
  //  }
  //}
}

/**
 * Process and log an edited item form.
 */
function guild_item_edit_submit($form, &$form_state) {
  guild_save_item($form_state['values']);
  
  $t_args = array('%name' => $form_state['values']['name']);
  if ($form_state['values']['item_op'] == 'add') {
    drupal_set_message(t('The item %name has been created', $t_args));
  }
  else {
    drupal_set_message(t('The item %name has been updated.', $t_args));
  }
  
  $form_state['redirect'] = 'admin/guild/items';
}

function guild_save_item(&$edit) {
  $t_args = array('%name' => $edit['name']);
  
  if ($edit['item_op'] == 'add') {
    drupal_write_record('guild_event_template', $edit);
    drupal_write_record('guild_item', $edit);
    watchdog('guild', 'item: added template %name', $t_args);
  }
  else if ($edit['item_op'] == 'edit') {
    // @todo Only update tables when necessary?
    drupal_write_record('guild_event_template', $edit, 'event_template_id');
    drupal_write_record('guild_item', $edit, 'event_template_id');
    watchdog('guild', 'item: updated template %name.', $t_args, WATCHDOG_NOTICE,
      l(t('edit'), 'admin/guild/items/' . $edit['event_template_id'] . '/edit'));
  }
}

/**
 * Form builder; Builds an item overview page.
 *
 * @see theme_guild_item_overview()
 *
 * @ingroup forms
 */
function guild_item_overview() {
  module_load_include('inc', 'guild', 'includes/guild.admin');
  $form = guild_admin_operations('items');
  
  $form['header'] = array(
    '#type' => 'value',
    '#value' => array(
      theme('table_select_header_cell'),
      array('data' => t('Name'), 'field' => 'name', 'sort' => 'asc'),
      array('data' => t('Link'), 'field' => 'link'),
    //array('data' => t('References'), 'field' => 'refs'),
      array('data' => t('Operations'))
    )
  );
  
  // Populate item table.
  $result = pager_query(
    "SELECT et.event_template_id AS id, et.name, et.description, i.link " .
    "FROM {guild_event_template} et " .
    "INNER JOIN {guild_item} i USING(event_template_id) " .
    "WHERE et.module = '%s' AND et.type = '%s' " .
  //"GROUP BY et.event_template_id " .
    tablesort_sql($form['header']['#value']), 50, 0, NULL, 'guild', 'item'
  );
  
  while ($item = db_fetch_object($result)) {
    $guild_items[$item->id] = '';
    
    $form['name'][$item->id] = array('#value' => check_plain($item->name));
    // @todo Truncate description to ~30 characters.
    // @todo Force the empty space for items with no descriptions?
    $form['description'][$item->id] = array('#value' => check_plain($item->description));
    // Automatic check_plain() as long as the HTML option is false (default).
    $form['link'][$item->id] = array('#value' => empty($item->link) ? '' : l($item->link, $item->link));
    //$form['refs'][$item->id] = array('#value' => $item->refs);
    $form['operations'][$item->id] = array('#value' => l(t('edit'), 'admin/guild/items/' . $item->id . '/edit'));
  }
  
  $form['items'] = array('#type' => 'checkboxes', '#options' => isset($guild_items) ? $guild_items : array());
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  
  return $form;
}

/**
 * Theme the item overview form.
 *
 * @ingroup themeable
 */
function theme_guild_item_overview($form) {
  drupal_add_css(drupal_get_path('module', 'guild') . '/guild.css');
  $output = drupal_render($form['update']);
  
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      $item = drupal_render($form['name'][$key]);
      if (!empty($form['description'][$key]['#value'])) {
        $description = drupal_render($form['description'][$key]);
        $item .= '<div class="guild-description">' . $description . "</div>\n";
      }
      
      $row = array();
      $row[] = drupal_render($form['items'][$key]);
      $row[] = $item;
      $row[] = drupal_render($form['link'][$key]);
    //$row[] = drupal_render($form['refs'][$key]);
      $row[] = drupal_render($form['operations'][$key]);
      
    //$rows[] = array('data' => $row, 'class' => 'guild-trow-height-large');
      $rows[] = $row;
    }
  }
  else {
    $rows[] = array(array('data' => t('No items available.'), 'colspan' => '4'));
  }
  
  $output .= theme('table', $form['header']['#value'], $rows, array('id' => 'guild-item-overview'));
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

/**
 * Helper function; Deletes an item from the database and logs any action.
 *
 * @see guild_delete_event(), guild_delete_raid()
 */
function guild_delete_item($item) {
  if (!is_object($item) || !is_numeric($item->event_template_id)) {
    watchdog('guild', 'Cannot delete a non-existant item.', array(), WATCHDOG_WARNING);
    return;
  }
  
  // Delete the item.
  db_query('DELETE FROM {guild_event_template} WHERE event_template_id = %d', $item->event_template_id);
  db_query('DELETE FROM {guild_item} WHERE event_template_id = %d', $item->event_template_id);
  watchdog('guild', 'item: deleted template %name.', array('%name' => $item->name));
  
  // @todo Notify other modules of a deleted item template.
  //guild_invoke_<your hook name>('delete', $item);
}

/**
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions
 * for existing items.
 * 
 * Note that spaces can cause HTTP 403 messages on some systems. See
 * http://drupal.org/node/333375 for more details.
 */
function guild_item_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range(
      "SELECT et.name FROM {guild_event_template} et " .
      "WHERE LOWER(et.name) LIKE LOWER('%%%s%%') AND et.module = '%s' AND et.type = '%s'",
      $string, 'guild', 'item', 0, 10
    );
    
    while ($item = db_fetch_object($result)) {
      $matches[$item->name] = check_plain($item->name);
    }
  }
  
  drupal_json($matches);
}
